dofile("../StylusBox2.lua")
dofile("../libColor.lua")

table.stringMax = function (t)
	local sizeMax, index = 0, 0
	for i = 1, #t do
		if type(t[i]) == "string" then
			if #t[i] > sizeMax then
				sizeMax, index =  #t[i], i
			end
		end
	end
	return sizeMax, index
end

ContextMenu = {
	new = function (x, y, choices)
		local folders = {}
		local done = {}
		local fileID = 0
		local fileLV = 0
		local isFile = false
		local isFolder = false
		
		skimTable = function(t, lv, x, y)
			local maxSize, maxSizeIndex = table.stringMax(t)
			
			if folders[lv] == nil then
				folders[lv] = {visible = false}
			end
			
			if folders[lv].visible then
				for i = 1, #t do
					local it = i
					local i1 = 0
					local i2 = i
					
					if type(t[i]) == "string" then
						for j = 1, #folders[lv] do
							for k = folders[lv][j][1], #t do
								if i == k then
									i = i-1
								end
							end
						end
						
						local x1, y1, x2, y2 = x, y+11*(i-1), x+maxSize*6+5, y+11*i+1
						
						screen.drawFillRect(SCREEN_DOWN, x1, y1, x2, y2, c_grey)
						screen.drawRect(SCREEN_DOWN, x1, y1, x2, y2, c_white)
						screen.print(SCREEN_DOWN, x1+2, y1+2, t[it], c_black)
						
						if StylusBox.simplePressed(x1, y1, x2, y2, Stylus.X, Stylus.Y) then
							Stylus.X, Stylus.Y = -1, -1
							for j = 1, #folders[lv] do
								for k =	folders[lv][j][1], #t do
									if it == k-1 then
										isFile = false
										isFolder = true
										folders[lv+1].visible = not folders[lv+1].visible
									else
										isFolder = false
										isFile = true
									end
								end
							end
							
							fileID, fileLV = i, lv
						end
					elseif type(t[i]) == "table" then
						if done[i] == nil then
							table.insert(folders[lv], {i})
							done[i] = true
						end
						for j = 1, #folders[lv] do
							for k = folders[lv][j][1], #t do
								if i == k then
									i2 = i2-(#folders-j)
								end
							end
						end
						
						skimTable(t[i], lv+1, x+maxSize*6+4, y+11*i2)
					end
				end
			end
		end
		
		local draw = function (self)
			skimTable(choices, 1, x, y)
		end
		
		local move = function (self, newX, newY)
			x, y = newX, newY
		end
		
		local setVisible = function(self, value, lv)
			if value == nil then value = true end
			if lv == nil then lv = 1 end
			folders[lv].visible = value
		end
		
		local getVisible = function(self, lv)
			if lv == nil then lv = 1 end
			return folders[lv].visible
		end
		
		local getInfos = function(self)
			local type = ""
			
			if isFile then
				type = "file"
			elseif isFolder then
				type = "folder"
			end
			
			return fileID, fileLV, type
		end
		
		local clear = function (self)
			self = nil
		end
		
		return {
			draw = draw,
			move = move,
			setVisible = setVisible,
			getVisible = getVisible,
			getInfos = getInfos,
			clear = clear
		}
	end
}
